package com.lej.player

import android.content.Context
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.model.VideoOptionModel
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import tv.danmaku.ijk.media.player.IjkMediaPlayer

class RTMPAudioPlayer(context: Context, url: String) {
    var videoPlayer: GSYVideoPlayer? = null

    init {
        /**此中内容：优化加载速度，降低延迟 */
        GSYVideoManager.instance().optionModelList = arrayListOf(
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_transport", "tcp"),
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_flags", "prefer_tcp"),
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "allowed_media_types", "video"),
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", 20000),
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 1316),
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "infbuf", 1), // 无限读
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 100),
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 10240),
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1),
            //  关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
            VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0),
        )
        videoPlayer = PlayerView(context).also { it.setUp(url, false, "") }
    }

    fun changeUrl(url: String) : RTMPAudioPlayer {
        videoPlayer?.setUp(url, false, "")
        return this
    }

    fun start() {
        videoPlayer?.startPlayLogic()
    }

    fun resume() {
        videoPlayer?.onVideoResume()
    }

    fun pause() {
        videoPlayer?.onVideoPause()
    }

    fun release() {
        videoPlayer?.release()
    }
}